<template>
  <el-dialog
    title="用户注册"
    :visible.sync="dialogVisible"
    width="600px"
    center
  >
    <!-- 中间表单部分 -->
    <!--
      model:表单对象
      rules:校验规则
     -->
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="80px"
      label-position="left"
    >
      <el-form-item label="头像" prop="avatar">
        <!--
          action:上传地址
          on-success:成功之后调用的方法，它里面做了俩件是，一是实现图片预览，二是给ruleForm.avatar赋值
          before-upload:上传之前，它里面做了俩件事，一是限制文件类型，大小，二是给后台需要的image属性赋值
          data:携带的额外参数
          imageUrl:图片预览
         -->
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :data="uploadObj"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="昵称" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" show-password></el-input>
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="16">
          <el-form-item label="图形码" prop="code">
            <el-input v-model="ruleForm.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <img
            :src="registerCaptcha"
            @click="changeRegisterCaptcha"
            style="width:100%;height:40px;"
            alt=""
          />
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="16">
          <el-form-item label="验证码" prop="rcode">
            <el-input v-model="ruleForm.rcode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button @click="getRcode">获取用户验证码</el-button>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'register',
  data () {
    return {
      imageUrl: '', // 头像上传的地址
      uploadUrl: process.env.VUE_APP_BASEURL + '/uploads', // 头像上传地址
      uploadObj: {
        image: null // image是后台要求的
      },
      registerCaptcha: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms',
      dialogVisible: false, // 决定对话框是否显示
      ruleForm: {
        username: '', // 昵称
        phone: '', // 手机
        email: '', // 邮箱
        avatar: '', // 头像
        password: '', // 密码
        code: '', // 图形码
        rcode: '' // 验证码
      },
      rules: {
        username: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: 'blur'
          }
        ],
        avatar: [
          {
            required: true,
            message: '头像不能为空',
            trigger: 'change'
          }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('邮箱不能为空'))
              }
              // 以下这行注释 告诉eslint注释的下一行不用管它
              // eslint-disable-next-line
              const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
              if (!reg.test(value)) {
                return callback(new Error('邮箱不规范'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('手机号不能为空'))
              }
              const reg = /^1[3456789][0-9]{9}$/
              if (!reg.test(value)) {
                return callback(new Error('手机号不规范'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          },
          { min: 6, max: 16, message: '密码长度为6到16位', trigger: 'blur' }
        ],
        rcode: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '验证码长度为4位',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '图形码不能为空',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '图形码为4位',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    dialogVisible (newValue) {
      if (!newValue) {
        // 清空表单内容
        this.$refs.ruleForm.resetFields()
        // 手动清空图像预览
        this.imageUrl = ''
      }
    }
  },
  methods: {
    // 切换验证码
    changeRegisterCaptcha () {
      this.registerCaptcha =
        process.env.VUE_APP_BASEURL +
        `/captcha?type=sendsms&t=${new Date() - 0}`
    },
    // 头像上传相关
    // 上传之后
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      console.log('图片地址', res)
      if (res.code === 200) {
        // 上传成功后 给ruleForm.avatar赋值
        this.ruleForm.avatar = res.data.file_path
      } else {
        // 上传失败
        this.$message.error(res.message)
      }
    },
    // 上传之前
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 上传的时候给image属性赋值
      this.uploadObj.image = file

      // 返回值为true才发起上传请求
      return isImage && isLt2M
    },
    // 获取验证码
    async getRcode () {
      // 校验部分，只校验手机号和图形码，validateField
      let num = 0
      this.$refs.ruleForm.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) {
          num++
        }
      })

      if (num === 2) {
        const res = await this.$axios.post('/sendsms', {
          phone: this.ruleForm.phone,
          code: this.ruleForm.code
        })

        if (res.code === 200) {
          this.ruleForm.rcode = res.data.captcha
        } else {
          // 提示
          this.$message.error(res.message)
          // 刷新图形码
          this.changeRegisterCaptcha()
        }
      }
    },
    submit () {
      // 全局校验
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return

        const res = await this.$axios.post('/register', this.ruleForm)
        if (res.code === 200) {
          // console.log('--注册--')
          // 提示
          this.$message.success('注册成功')

          // 关闭对话框
          this.dialogVisible = false
        } else {
          // 提示
          this.$message.error(res.message)

          // 刷新验证码
          this.changeRegisterCaptcha()
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep.avatar-uploader {
  text-align: center;
}
::v-deep.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
::v-deep.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
